<!--
 * @Description: 
 * @Version: 0.0
 * @Author: taosong
 * @Date: 2023-03-22 20:22:21
 * @LastEditors: taosong
 * @LastEditTime: 2023-03-24 21:09:04
-->
<template>
  <div class="table-con">
    <Table
      border
      :columns="tableHead"
      :data="tableData"
      v-bind="$attrs"
    >
      <template
        v-for="(item, indexs) in slotArray"
        :key="indexs"
        #[item.action]="{ row, column }"
      >
        <template
          class="edit"
          v-if="currentEdit === row._rowKey + column._columnKey + column.__id"
        >
          <Input v-model="row[item.action]" />
          <Icon
            @click="editSaveClick(row)"
            type="md-checkmark"
          />
          <Icon
            @click="editCloseClick(row)"
            type="md-close"
          />
        </template>

        <template v-else>
          <slot
            :name="item.action"
            :data="{ row, column }"
          ></slot>
          <Icon
            @click="editClick(row, column)"
            type="md-construct"
            v-if="item.editable"
          />
        </template>
      </template>
    </Table>
  </div>
</template>

<script lang="ts">
const EMITS_EDIT_SAVE_CLICK = 'editSaveClick'
</script>

<script setup lang="ts">
import { PropType, ref } from 'vue'
import { TableData, TableOptions } from './types'

const props = defineProps({
  tableHead: {
    type: Array as PropType<TableOptions[]>,
    required: true
  },
  tableData: {
    type: Array as PropType<TableData[]>,
    required: true
  },
  // 自定义列slot name
  slotArray: {
    type: Array as PropType<any[]>,
    required: true
  }
})

// 分发事件
const emits = defineEmits([EMITS_EDIT_SAVE_CLICK])

// 保存一份唯一标识
const currentEdit = ref('')
// 保存一份内容
const rowContent = ref('')

// 点编辑图标
const editClick = (row: any, column: any) => {
  // 保存一份内容
  rowContent.value = ''
  rowContent.value = row.name
  // 保存一份唯一标识
  currentEdit.value = row._rowKey + column._columnKey + column.__id
}

//  编辑后的保存编辑
const editSaveClick = (row: any) => {
  emits(EMITS_EDIT_SAVE_CLICK, row)
  currentEdit.value = ''
}
// 取消编辑
const editCloseClick = (row: any) => {
  if (row!.name !== rowContent.value) {
    row.name = rowContent.value
  }
  currentEdit.value = ''
}
</script>

<style lang="scss"></style>
